﻿namespace LeetCodeProject._0001_1000._101_200._101_110._102;

public class Solution
{
    public IList<IList<int>> LevelOrder(TreeNode root)
    {
        if (root == null)
            return new List<IList<int>>();
        IList<TreeNode> prev = new[] { root };
        var result = new List<IList<TreeNode>>();
        while (prev.Count > 0)
        {
            result.Add(prev);
            prev = new List<TreeNode>();
            foreach (var node in result.Last())
            {
                if (node == null)
                    continue;
                if (node.left != null)
                    prev.Add(node.left);
                if (node.right != null)
                    prev.Add(node.right);
            }
        }

        return result.Select(t => t.Select(n => n.val).ToArray() as IList<int>).ToArray();
    }
}